package com.detrum.sportcamera.nfstask;

import android.os.AsyncTask;

import com.detrum.NFSVideo;
import com.detrum.utils.LogUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by abc on 2018/3/20.
 */

public class NfsWriteDeviceFile extends AsyncTask<String,Integer,Void> {
    private int index;
    private WriteDevcieFileCall writeDevcieFileCall;

    public NfsWriteDeviceFile(int index, WriteDevcieFileCall writeDevcieFileCall) {
        this.index = index;
        this.writeDevcieFileCall = writeDevcieFileCall;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        writeDevcieFileCall.finish();
    }

    @Override
    protected Void doInBackground(String... strings) {
        String[] str = strings[0].split("/");
        LogUtils.i("strings[0] = "+strings[0]);
        File file = new File(strings[0]);
        if(!file.exists()){
            writeDevcieFileCall.FileEmpty();
            return null;
        }
        String name = str[str.length-1];
        String nfsPath = "/"+name;
        LogUtils.i("nfsPath = "+nfsPath);
        int create = NFSVideo.create(nfsPath,index);
        LogUtils.i("create = "+create);
        writeDevcieFileCall.DeviceUpdate(1);
        byte[]data = new byte[102400];
        try {
            FileInputStream fis = new FileInputStream(file);
            while (true){
                int length = fis.read(data);
                if(length!=-1){
                    int write = NFSVideo.write(data,length,index);
                }else{
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            LogUtils.i("FileNotFoundException");
            e.printStackTrace();
        } catch (IOException e) {
            LogUtils.i("IOException");
            e.printStackTrace();
        }
        writeDevcieFileCall.DeviceUpdate(2);
        return null;
    }
}
